package biz.datalk.industrialland.common.util;

import org.apache.commons.lang3.StringUtils;

import java.util.Arrays;

/**
 * 字符串脱敏工具
 *
 * @author tarofang@163.com
 * @date 2024-01-16
 */
public class DesensitizeUtil {
    public static final String DELIM_ASTERISK = "*";
    public static final int DEFAULT_ASTERISK_NUM = 6;

    public static String desensitizeMobile(String mobile) {
        return desensitize(mobile, 3, 4);
    }

    public static String desensitize(String str, int start, int end) {
        if (StringUtils.isBlank(str)) {
            return str;
        }

        start = start <= 0 ? DEFAULT_ASTERISK_NUM : start;
        end = end <= 0 ? DEFAULT_ASTERISK_NUM : end;

        int len = StringUtils.length(str);
        int sum = start + end;
        if (len > sum) {
            return str.substring(0, start) + genAsterisk(len - sum, DEFAULT_ASTERISK_NUM) + str.substring(len - end);
        }

        int minLen = 2;
        if (len > minLen) {
            return str.charAt(0) + genAsterisk(len - minLen, DEFAULT_ASTERISK_NUM) + str.charAt(len - 1);
        }

        return genAsterisk(DEFAULT_ASTERISK_NUM, DEFAULT_ASTERISK_NUM);
    }


    public static String genAsterisk(int num, int max) {
        if (num <= 0) {
            return StringUtils.EMPTY;
        }

        if (max <= 0) {
            return StringUtils.EMPTY;
        }

        int len = Math.min(num, max);
        String[] arr = new String[len];
        Arrays.fill(arr, DELIM_ASTERISK);

        return StringUtils.join(arr);
    }

    public static void main(String[] args) {
        String x = "12";
        String s = desensitizeMobile(x);
        System.out.println("s = " + s);
    }

}
